package com.server.game;

import com.server.orm.OrmTransaction;
import com.server.util.LogUtil;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 执行过程分配器
 */
public class TransactionDispatcher extends Thread {

    public static int QUEUE_MAX = 1000;//每次最多处理数量

    private volatile boolean start = false;

    private volatile boolean interrupt = false;//线程是否被中断

    private static long TICK_PER = 1L;

    private LinkedBlockingQueue<OrmTransaction> tQueue = new LinkedBlockingQueue<>();

    public TransactionDispatcher() {

    }

    public void startUp() {
        this.start = true;
        this.start();
    }

    public void close() {
        LogUtil.game.info("TransactionDispatcher close begin");
        this.start = false;
        try {
            while (true) {
                Thread.sleep(TICK_PER);
                if (interrupt) {
                    this.interrupt();
                    break;
                }
            }
        } catch (InterruptedException e) {
            LogUtil.game.error("Exception", e);
        }
        LogUtil.game.info("TransactionDispatcher close end");
    }

    @Override
    public void run() {
        while (this.start && !interrupt) {
            try {
                Thread.sleep(TICK_PER);
            } catch (InterruptedException e) {
                LogUtil.game.error("Exception", e);
                break;
            }
            //每次最多处理n个协议
            List<OrmTransaction> list = new LinkedList<>();
            tQueue.drainTo(list, this.start == false ? Integer.MAX_VALUE : QUEUE_MAX);
            list.forEach(t -> {
                if (null == t) {
                    return;
                }
                t.execute();
            });
            if (this.start == false) {
                this.interrupt = true;
            }
        }
    }

    public void addOrmTransaction(OrmTransaction ormTransaction) {
        if (!this.start) {
            return;
        }
        tQueue.add(ormTransaction);
    }
}
